package com.hyh.eblog.template;

import com.hyh.eblog.common.templates.DirectiveHandler;
import com.hyh.eblog.common.templates.TemplateDirective;
import com.hyh.eblog.util.RedisUtil;
import org.apache.ibatis.annotations.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Component;
import org.springframework.validation.annotation.Validated;

import javax.annotation.Resource;
import java.util.*;

/**
 * 自定义标签 本周热议
 * @author Summerday
 */
@Component
public class WeekRankTemplate extends TemplateDirective {

    @Resource
    RedisUtil redisUtil;

    @Override
    public String getName() {
        return "weekHots";
    }

    @Override
    public void execute(DirectiveHandler handler) throws Exception {
        // 获取redis中的值
        String weekKey = "week:rank";
        Set<ZSetOperations.TypedTuple<Object>> typedTuples = redisUtil.getZSetRank(weekKey, 0, 6);
        List<Map<String, Object>> hotPosts = new ArrayList<>();
        for (ZSetOperations.TypedTuple<Object> tuple : typedTuples) {
            Map<String, Object> map = new HashMap<>();
            Object postId = tuple.getValue(); //post id
            String postKey = "rank:post:" + postId;
            map.put("id", postId);
            map.put("title",redisUtil.hget(postKey,"post:title"));
            map.put("commentCount",tuple.getScore());
            hotPosts.add(map);
        }
        handler.put(RESULTS,hotPosts).render();
    }
}
